package com.example.crm.service;
import com.example.crm.entity.Users;
import com.example.crm.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UsersService {
    @Autowired
    private UsersRepository UsersRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 注册
    public Users register(Users users) {
        if (UsersRepository.findByUsername(users.getUsername()).isPresent()) {
            throw new IllegalStateException("错误：用户名 '" + users.getUsername() + "' 已被注册！");
        }
        String encodedPassword = passwordEncoder.encode(users.getPassword());
        users.setPassword(encodedPassword);

        if (users.getRole() == null || users.getRole().isEmpty()) {
            users.setRole("普通员工");
        }
        return UsersRepository.save(users);
    }

    // 登录
    public Optional<Users> login(String username, String rawPassword) {
        Optional<Users> optionalUser = UsersRepository.findByUsername(username);
        if (optionalUser.isPresent()) {
            Users users = optionalUser.get();
            if (passwordEncoder.matches(rawPassword, users.getPassword())) {
                return optionalUser;
            }
        }
        return Optional.empty();
    }

    // 查询所有用户
    public List<Users> findAll() {
        return UsersRepository.findAll();
    }

    // 保存用户
    public Users save(Users users) {
        validatePhone(users.getPhone());
        if (users.getPassword() != null && !users.getPassword().isEmpty()&& !users.getPassword().startsWith("$2a$")) {
            users.setPassword(passwordEncoder.encode(users.getPassword()));
        }
        return UsersRepository.save(users);
    }

    // 根据ID删除用户
    public void deleteById(Integer id) {
        UsersRepository.deleteById(id);
    }

    // 根据ID查找用户
    public Optional<Users> findById(Integer id) {
        return UsersRepository.findById(id);
    }


    //修改密码
    public boolean changePassword(String username, String oldPwd, String newPwd) {
        Optional<Users> userOpt = UsersRepository.findByUsername(username);
        if (userOpt.isPresent()) {
            Users user = userOpt.get();
            if (passwordEncoder.matches(oldPwd, user.getPassword())) {
                String encodedNewPassword = passwordEncoder.encode(newPwd);
                user.setPassword(encodedNewPassword);
                Users savedUser = UsersRepository.save(user);
                return true;
            }else {
            System.out.println("原密码验证失败");
            return false;
        }
    } else {
            System.out.println("用户不存在: " + username);
            return false;
        }
    }
    //检查电话号
    private void validatePhone(String phone) {
        if (phone != null && !phone.isEmpty() && phone.length() != 11) {
            throw new IllegalArgumentException("电话号码位数错误，必须是11位！");
        }
    }
}